import Vue from 'vue'
import axios from 'axios'
import store from '../store'
import { serialize, logout } from '@/utils/utils'

const request = axios.create({
  timeout: 60000
})

request.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500
}

//跨域请求，允许保存cookie
request.defaults.withCredentials = true

request.interceptors.request.use(
  (config) => {
    if (store.state.common.token) {
      config.headers['X-Access-Token'] = store.state.common.token
    }

    if (config.text === true) {
      config.headers['Content-Type'] = 'text/plain'
    }

    //headers中配置serialize为true开启序列化
    const meta = config.meta || {}
    if (config.method === 'post' && meta.isSerialize === true) {
      config.data = serialize(config.data)
    }
    return config
  },
  () => {
    Vue.$toast('服务器出错，请稍后再操作！', {
      type: 'error'
    })
  }
)

request.interceptors.response.use(
  (res) => {
    const status = res.data ? res.data.code : ''
    const message = res.data.message || res.data.msg || '服务器出错，请稍后尝试！'

    if (res && res.data && res.data.repCode) {
      return res.data
    } else if (status === 401 || status === 10001) {
      Vue.$toast('登录信息已过期，请重新登录！', {
        type: 'error'
      })
      logout()
    } else if (status !== 200) {
      Vue.$toast(message, {
        type: 'error'
      })
      return { success: false }
    } else {
      return res.data
    }
  },
  () => {
    Vue.$toast('服务器出错，请稍后再操作！', {
      type: 'error'
    })
  }
)

export default request
